<template>
  <GlobalContainer :needLogin="true" showTabBar :backgroundImage="`${OSS_URL}/images/home/home_banner.png`">
    <GlobalHeader :backgroundImage="`${OSS_URL}/images/home/home_banner.png`" :fixed="true" />
    <div class="px-23">
      <div>
        <template v-if="token">
          <div class="username">您好{{ userInfo.realName || userInfo.userName }}，欢迎回家！</div>
          <div class="address flex items-center" @tap="toPageHandle('/subPages/home/index')">
            <div class="flex flex-col">
              <div>{{ accountStore.roomInfo }}</div>
              <div class="h-40" v-if="accountStore.currentRoom && accountStore.currentRoom.region">
                {{ accountStore.currentRoom.region }} {{ accountStore.currentRoom.smallAddress }}
              </div>
            </div>
            <image class="ml-10 h-33 w-32" src="../../static/images/home/loc_right.png" />
          </div>
        </template>
        <template v-else>
          <div class="username">中鹊物业 欢迎您！</div>
          <div class="address flex items-center" @tap="toPageHandle('/subPages/home/index')">
            <span>登录后享更多物业服务</span>
            <image class="ml-10 h-33 w-32" src="../../static/images/home/loc_right.png" />
          </div>
        </template>
      </div>
      <!-- 公告 -->
      <div class="notice relative">
        <image class="absolute right-0 top-0 z-0 h-125 w-176" :src="`${OSS_URL}/images/home/gongzhi_bg.png`" />
        <div class="relative" @tap="switchToPageHandle('/pages/notification/index')">
          <div class="flex items-center">

            <span class="text-[#1E2E4C]">通知</span>
            <span class="text-[#1E90FF]">公告</span>
            <image class="ml-10 h-12 w-11" src="../../static/images/home/tongzhi_right.png" />
          </div>
          <p class="text" v-if="accountStore.notificationList[0]?.title">{{ accountStore.notificationList[0]?.title }}</p>
          <p class="text" v-else>暂无公告～</p>
        </div>
      </div>

      <!-- 服务 -->
      <div class="services-c relative">
        <image class="relative z-0 size-full" :src="`${OSS_URL}/images/home/changyong_bg.png`" />
        <div class="z-10 absolute left-0 top-0 size-full">
          <div class="services-title">常用服务</div>
          <div class="service-item-wrap px-10">
            <div class="service-item" v-for="item in pageList" :key="item.name" @tap.stop="toPageHandle(item.path)">
              <div class="service-icon">
                <image :src="item.icon" />
              </div>
              <p class="whitespace-nowrap text-28">{{ item.name }}</p>

              <button v-if="!item.notCheckRoom && !accountStore.userInfo.roomId" class="login-button" @tap.stop="toRoomListHandle" />
            </div>
          </div>
        </div>
      </div>

      <div class="banner relative mb-28 mt-20" @tap="toPageHandle('/subPages/wuye/list')">
        <image class="h-240 w-full" :src="`${OSS_URL}/images/home/buttom_banner.png`" />
        <div class="absolute bottom-20 right-30 flex items-center text-24 text-[#3A8FFF]">
          <span>去看看</span>
          <image class="ml-10 h-12 w-11" src="../../static/images/home/tongzhi_right.png" />
        </div>
      </div>

      <!-- 新增漂浮小方块 -->
  <div 
    v-if="showFloatBox" class="float-box" :style="floatStyle" @click="toPageHandle('/subPages/wuye/list')">
    <button class="close-btn" @click.stop="toggleFloatBox">×</button>
    <image class="icon" :src="`${OSS_URL}/images/home/moveimg.png`"/>
  </div>

    </div>
  </GlobalContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import GlobalHeader from '@/components/GlobalHeader/index.vue'
import { getCommunityPage } from '@/common/api/common'
import { showToast, showModal } from '@/utils/message'
import { useAccountStore } from '@/store/modules/account'

const OSS_URL = import.meta.env.VITE_OSS_URL
const accountStore = useAccountStore()

const token = computed(() => accountStore.token)
const userInfo = computed(() => accountStore.userInfo)

const showPhone = () => {
  getCommunityPage({ pageNo: 1, pageSize: 9999 }).then((res: any) => {
    const communityId = accountStore.currentRoom.communityId
    const phone = res.records.find((item: any) => item.id === communityId)?.contactPhone ?? ''
    if (phone) {
      showModal({
        title: '管家电话',
        content: phone,
        confirmText: '确定'
      })
    } else {
      showToast('暂无管家电话')
    }
  })
}

const pageList = [
  {
    name: '物业缴费',
    icon: `${OSS_URL}/images/home/wuyejiaofei.png`,
    path: '/subPages/jiaofei/index'
  },
  {
    name: '报事报修',
    icon: `${OSS_URL}/images/home/baoxiu.png`,
    path: '/subPages/baoxiu/index'
  },
  {
    name: '装修办理',
    icon: `${OSS_URL}/images/home/zhuangxiu.png`,
    path: '/subPages/zhuangxiu/index'
  },
  {
    name: '我的管家',
    icon: `${OSS_URL}/images/home/guanjia.png`,
    path: 'showPhone'
  },
  {
    name: '物业+居家养老',
    icon: `${OSS_URL}/images/home/yanglao.png`,
    path: '/subPages/wuye/list',
    notCheckRoom: true
  },
  {
    name: '物品借用',
    icon: `${OSS_URL}/images/home/jieyong.png`,
    path: '/subPages/jieyongLog/index'
  },
  {
    name: '投诉建议',
    icon: `${OSS_URL}/images/home/tousu.png`,
    path: '/subPages/tousu/index'
  },
  {
    name: '更多服务',
    icon: `${OSS_URL}/images/home/genduo.png`,
    path: '/subPages/gengduo/index'
  }
]

const toRoomListHandle = () => {
  showModal({
    title: '提示',
    content: '请绑定房源或等待房源审核通过',
    success: () => {
      uni.navigateTo({
        url: '/subPages/home/index'
      })
    },
    cancel: () => {}
  })
}
// onShow(async () => {
//   const userInfo = await getUserInfo()
//   console.log('[ userInfo ] >', userInfo)
// })
// const getUserInfo = async () => {
//   accountStore.getUserInfoByToken()
// }

const toPageHandle = (path: string) => {
  if (path === 'showPhone') {
    showPhone()
    return
  }
  uni.navigateTo({
    url: path
  })
}
const switchToPageHandle = (page: string) => {
  uni.switchTab({
    url: page
  })
}

// 新增响应式数据
const showFloatBox = ref(true)
const floatPos = reactive({ x: 50, y: 50 })
const moveDirection = reactive({ dx: 1, dy: 1 })

// 漂浮动画逻辑
const speed = 2
let intervalId: number | null = null
const updatePosition = () => {
  if (!showFloatBox.value) return
  
  const maxX = uni.getSystemInfoSync().windowWidth - 100
  const maxY = uni.getSystemInfoSync().windowHeight - 100
  
  floatPos.x += moveDirection.dx * speed
  floatPos.y += moveDirection.dy * speed

  // 边界检测
  if (floatPos.x <= 0 || floatPos.x >= maxX) moveDirection.dx *= -1
  if (floatPos.y <= 0 || floatPos.y >= maxY) moveDirection.dy *= -1

  // requestAnimationFrame(updatePosition)
}

onMounted(() => {
  intervalId = setInterval(updatePosition, 100) // 每16毫秒更新一次位置
})

// 关闭按钮方法
const toggleFloatBox = () => {
  showFloatBox.value = !showFloatBox.value
  if (!showFloatBox.value && intervalId !== null) {
    clearInterval(intervalId)
    intervalId = null
  }
}

// 计算样式
const floatStyle = computed(() => ({
  left: `${floatPos.x}px`,
  top: `${floatPos.y}px`,
  // transform: `rotate(${floatPos.x * 0.5}deg)` // 增加旋转效果
}))
</script>

<style lang="scss" scoped>
page {
  background-color: #f3f3f3;
}
.username {
  font-size: 40rpx;
  color: #ffffff;
  line-height: 60rpx;
}
.notice {
  height: 140rpx;
  background: linear-gradient(#fafcff 0%, #e8f3ff 100%);
  border-radius: 20rpx;
  border-image: linear-gradient(180deg, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0)) 2 2;
}
.address {
  font-weight: 400;
  font-size: 34rpx;
  color: #ffffff;
  line-height: 52rpx;
  margin-top: 24rpx;
}
.notice {
  margin-top: 60rpx;
  padding: 22rpx 16rpx 16rpx 32rpx;
  font-weight: bold;
  font-size: 32rpx;
  line-height: 44rpx;
  .text {
    margin-top: 10rpx;
    font-weight: 400;
    font-size: 28rpx;
    line-height: 50rpx;
    color: #406586;
    // 超出部分隐藏
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.services-c {
  margin-top: 20rpx;
  height: 570rpx;
  border-radius: 12rpx;
  box-shadow: 0rpx 2rpx 15rpx -5rpx #e2efff;
  overflow: hidden;
  .services-title {
    height: 104rpx;
    line-height: 104rpx;
    font-weight: bold;
    font-size: 34rpx;
    color: #353535;
    font-style: normal;
    text-transform: none;
    margin-left: 30rpx;
  }
  .service-item-wrap {
    background-color: #fff;
    padding-top: 54rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    padding-bottom: 24rpx;
    border-radius: 0 0 12rpx 12rpx;
    .service-item {
      position: relative;
      margin-bottom: 44rpx;
      width: 25%;
      display: flex;
      flex-direction: column;
      align-items: center;
      .service-icon {
        width: 104rpx;
        height: 117rpx;
        image {
          width: 100%;
          height: 100%;
          font-size: 0;
        }
      }
      p {
        font-size: 28rpx;
        color: #353535;
        line-height: 36rpx;
        letter-spacing: 1px;
        text-align: center;
        font-style: normal;
        text-transform: none;
      }
    }
  }
}

.login-button {
  position: absolute;
  z-index: 9999;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

//新增
.float-box {
  position: fixed;
  width: 200rpx;
  height: 200rpx;
  background: #3A8FFF;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.15);
  transition: all 0.3s ease;
  z-index: 999;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  .icon {
    width: 200rpx;
    height: 200rpx;
    transition: transform 0.3s;
  }

  &:active {
    transform: scale(0.95);
  }

  .close-btn {
    position: absolute;
    right: 4rpx;
    top: 4rpx;
    width: 32rpx;
    height: 32rpx;
    line-height: 28rpx;
    text-align: center;
    background: rgba(0,0,0,0.3);
    color: white;
    border-radius: 50%;
    font-size: 24rpx;
    z-index: 1000;
    border: none;
  }

  &::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    border: 2rpx solid rgba(255,255,255,0.2);
    border-radius: 8rpx;
    pointer-events: none;
  }
}
</style>
